#include "handler_base.h"
#include "spdlog/spdlog.h"

namespace simple {
    std::mutex HandlerBase::mux;
    std::map<std::string, std::vector<std::shared_ptr<HandlerBase>>> HandlerBase::handlerMap_;

    const std::map<std::string, std::vector<std::shared_ptr<HandlerBase>>> &HandlerBase::getHandlers() {
        return handlerMap_;
    }

    void HandlerBase::resetHandlers() {
        std::lock_guard<std::mutex> lock(mux);
        for (const auto &item: HandlerBase::handlerMap_) {
            for (const auto &handler: item.second) {
                handler->unRegister_hook();
            }
        }
        HandlerBase::handlerMap_.clear();
    }

    bool HandlerBase::registerHandler(const std::shared_ptr<HandlerBase> &handler) {
        std::lock_guard<std::mutex> lock(mux);
        if (handler->eventName().empty()) {
            spdlog::warn("registration failed, event name cannot be empty");
            return false;
        }

        if (!HandlerBase::handlerMap_.count(handler->eventName())) {
            std::vector<std::shared_ptr<HandlerBase>> handlers;
            HandlerBase::handlerMap_.insert(std::make_pair(handler->eventName(), handlers));
        }
        for (const auto &item: HandlerBase::handlerMap_.at(handler->eventName())) {
            if (item == handler) {
                spdlog::warn("registration failed, the handler has been registered");
                return false;
            }
        }
        HandlerBase::handlerMap_.at(handler->eventName()).push_back(handler);
        handler->register_hook();
        return true;
    }

    bool HandlerBase::unRegisterHandler(const std::shared_ptr<HandlerBase> &handler) {
        std::lock_guard<std::mutex> lock(mux);
        if (handler->eventName().empty()) {
            return false;
        }
        if (!HandlerBase::handlerMap_.count(handler->eventName())) {
            return false;
        }

        auto &handlers = HandlerBase::handlerMap_.at(handler->eventName());
        for (auto it = handlers.begin(); it < handlers.end(); ++it) {
            if (*it == handler) {
                handlers.erase(it);
                handler->unRegister_hook();
                if (handlers.empty()) {
                    // 没有处理器, 事件名称一同删除
                    HandlerBase::handlerMap_.erase(handler->eventName());
                }
                return true;
            }
        }
        return false;
    }

    bool HandlerBase::publishEvent(const std::string &event_name, Session *const session) {
        std::lock_guard<std::mutex> lock(mux);
        if (!HandlerBase::handlerMap_.count(event_name)) {
            return false;
        }
        auto &handlers = HandlerBase::handlerMap_.at(event_name);
        for (const auto &handler: handlers) {
            handler->onEvent(session);
        }
        return true;
    }

    HandlerBase::~HandlerBase() = default;
}